﻿package kr.pfg.pfgTracer.model
{
	import flash.events.AsyncErrorEvent;
	import flash.events.EventDispatcher;
	import flash.events.SecurityErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	
	import kr.pfg.pfgTracer.model.event.ReceiveMessageEvent;
	import kr.pfg.pfgTracer.model.event.ReceiveSwfInfoEvent;
	import kr.pfg.pfgTracer.model.vo.EchoClient;
	
	public class ReceiveManager extends EventDispatcher
	{
		private var lc: LocalConnection;		
		private var clientMember: Array;
		
		public function ReceiveManager()
		{		
			clientMember = new Array();
			
			lc = new LocalConnection();
			lc.addEventListener( AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler );
			lc.addEventListener( SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler );
			lc.addEventListener( StatusEvent.STATUS, statusHandler );
			lc.allowDomain( "*" );
			lc.client = this;
			try
			{				
				lc.connect( "_pfgTracer" );				
				
			}catch ( error: ArgumentError )
			{
				this.dispatchEvent( new ReceiveMessageEvent ( ReceiveMessageEvent.DATA_ERROR ) );
			}			
			
		}
		
		private function asyncErrorHandler ( e: AsyncErrorEvent ): void
		{
			trace ( " [ AsyncErrorEvent ] " );
		}
		
		private function securityErrorHandler ( e: SecurityError ): void
		{
			trace ( " [ SecurityError  ] " );
		}
		
		private function statusHandler ( e: StatusEvent ): void
		{
			trace ( " [ StatusEvent ] " ) ;
		}
		
		private var echoClient: EchoClient;		
		public function startHandler ( key: String ): void 
		{
			// 새로운 Handler 시작할때마다 새로운 LocalConnect 를 생성해준다
			this.echoClient = new EchoClient ( key );			
			this.clientMember.push( echoClient );
			
			
			 // EchoClient 로 날라오는 Message 와 type 을 보내주는 Event
			this.echoClient.addEventListener( ReceiveMessageEvent.DATA_RECEIVED, receiverHandler );
			
			// swfInformation 을 보내주는 Event
			this.echoClient.addEventListener( ReceiveSwfInfoEvent.DATA_SWFINFORMATION, informationHandler );			
		}
		
		private function receiverHandler ( e: ReceiveMessageEvent ): void
		{
			var data: Object = e.data;
			data.key = e.currentTarget.key;
			this.dispatchEvent( new ReceiveMessageEvent ( ReceiveMessageEvent.DATA_RECEIVED, data ) );
		}
		
		private function informationHandler ( e: ReceiveSwfInfoEvent ): void
		{
			//this.dispatchEvent( new ReceiveSwfInfoEvent ( ReceiveSwfInfoEvent.DATA_SWFINFORMATION, clientMember ) );
			this.dispatchEvent( new ReceiveSwfInfoEvent ( ReceiveSwfInfoEvent.DATA_SWFINFORMATION, e.currentTarget ) );
		}
	}
}